
import { useState, useCallback, useEffect } from 'react';
import { Button, Input, Message, Space, Typography, Select, Form } from '@arco-design/web-react';
import { useLocalStorageState } from 'ahooks';


import { useTRPC, useTRPCClient } from '@server/trpc/client';
import { useStorageForm } from '@hooks/useStorageForm';
import { MODELS_STORAGE_KEY } from '@constants/models';
import { Model } from '../../../../app/applications/model-manager/page';

type IProps = {
  value?: string;
  onChange?: (value: string) => void;
}

const STORAGE_KEY = 'ai_prompt_cache';

type FormType = {
  description: string;
  modelId: string;
}

function AIGenerateInput({ value, onChange }: IProps) {
  const [models] = useLocalStorageState<Model[]>(MODELS_STORAGE_KEY, { defaultValue: [] });
  const [loading, setLoading] = useState(false);
  const { form, saveForm } = useStorageForm<FormType>({ storageKey: STORAGE_KEY, ignoreFields: [] });

  const { image } = useTRPCClient();
  
  const handleGenerate = async () => {
    form.validate().then(async (value) => {
      console.log(value);

      const { description, modelId } = value



      setLoading(true);
      saveForm()
      const model = models.find(item => item.id === modelId)
      try {
        const prompt = await image.generatePrompt.mutate({
          description,
          modelConfig: model!,
        });

        onChange?.(prompt);
      } catch (err) {
        console.log(err);
      
        Message.error('生成失败，请重试');
      } finally {
        setLoading(false);
      }
    })


  };

  return (
    <Form form={form} labelCol={{ span: 2 }} onSubmit={handleGenerate} size="mini" layout='horizontal'>
      <Form.Item className="mb-0" rules={[{ required: true }]} label="模型" required field="modelId">
        {models.length > 0 && (
          <Select
            placeholder="选择AI模型"
            className="mb-4"
          >
            {models.map(model => (
              <Select.Option key={model.id} value={model.id}>
                {model.name} ({model.model})
              </Select.Option>
            ))}
          </Select>
        )}
      </Form.Item>
      <Form.Item rules={[{ required: true }]} required label='描述' field="description">
        <Input.TextArea
          placeholder="描述你想要的画面，AI将生成提示词，如：一个女孩走在海滩上"
          autoSize
        />
      </Form.Item>
      <Form.Item>
        <Button 
          type="primary" 
          loading={loading}
          size="mini"
          onClick={handleGenerate}
        >
        生成提示词
        </Button>
      </Form.Item>
      {value && (
        <div className="mt-2">
          <Typography.Text bold>生成的提示词: </Typography.Text>
          <Typography.Text>{value}</Typography.Text>
        </div>
      )}
    </Form>
  );
}

export default AIGenerateInput;